package com.ghxxzx.daglcustom.business_fk.file.web;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.base.ne.NePage;
import org.tmsps.ne4spring.utils.DateTools;
import org.tmsps.ne4spring.utils.FileTools;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import com.ghxxzx.daglcustom.business_fk.file.domain.FilePo;
import com.ghxxzx.daglcustom.business_fk.file.domain.dto.FileQuery;
import com.ghxxzx.daglcustom.business_fk.file.service.FileService;
import com.ghxxzx.daglcustom.utils.WebUtil;
import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping("/cp/file")
public class FileAction extends BaseAction {

	@Autowired
	private FileService fileService;

	@Value("${app.filepath}")
	private String filepath;

	@GetMapping("/list")
	public Wrapper<NePage> list(FileQuery fileQuery) {
		NePage page = fileService.selectFile(fileQuery);
		return WrapMapper.ok(page);
	}

	@GetMapping("/delete")
	public Wrapper<String> delete(String kid) {
		FilePo file = bs.findById(kid, FilePo.class);
		file.setStatus(-100);
		bs.updateObj(file);
		return WrapMapper.ok("删除成功");
	}

	/*
	 * . activiti 上传文件
	 */
	@PostMapping("/upload_activiti")
	public String upload_activiti(@RequestParam MultipartFile file) throws IllegalStateException, IOException {
		String suffix = FileTools.getSuffix(file.getOriginalFilename());
		String filename = System.currentTimeMillis() + "." + suffix;
		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folderUrl = year + "/" + month;
		// 保存文件
		FilePo tf = new FilePo();
		tf.setFile_name(file.getOriginalFilename());
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setFolder_url(folderUrl);
		tf.setContent_type(file.getContentType());
		tf.setSize(file.getSize());
		// 获取保存路径
		String DATA_PATH = filepath;
		File newFile = new File(DATA_PATH + File.separator + folder + File.separator + tf.getNew_file_name());
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		file.transferTo(newFile);
		bs.saveObj(tf);

		JSONObject end = new JSONObject();
		end.put("code", 200);
		end.put("msg", "上传成功");
		end.put("url", WebUtil.getRequest().getContextPath() + "/download/" + tf.getKid());
		end.put("name", tf.getFile_name());
		end.put("kid", tf.getKid());
		return end.toJSONString();
	}

}
